package com.zl.rbac.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zl.rbac.entity.Permission;
import com.zl.rbac.entity.Role;
import com.zl.rbac.mapper.PermissionMapper;
import com.zl.rbac.mapper.RoleMapper;
import com.zl.rbac.mapper.RolePermissionMapper;
import com.zl.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.List;

@Service
public class RoleServiceImpl  implements IRoleService{
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private PermissionMapper  permissionMapper;

    @Override
    public Page<Role> queryByPage(Integer pageIndex, Integer pageSize) throws Exception {
        Page<Role> page = new Page<>(pageIndex,pageSize);
        //设置排序, 根基id升序排序
        page.addOrder(new OrderItem("id",true));
        roleMapper.selectPage(page,null);
        return page;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Serializable id) throws Exception {
        roleMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(Role role) throws Exception {
        //保存角色
        roleMapper.insert(role);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role role) throws Exception {
        //修改角色信息
        roleMapper.updateById(role);



    }

    @Override
    public Role queryById(Serializable id) throws Exception {
        return roleMapper.selectById(id);
    }

    @Override
    public List<Role> queryAll() throws Exception {
        return roleMapper.selectList(null);
    }

    @Transactional(rollbackFor = Exception.class)
    public void save(Role role,Integer[] ids) throws Exception {
        //保存角色
         this.save(role);
        //保存角色分配的权限
        if(ids != null &&  ids.length > 0){
            for (Integer pid : ids) {
                rolePermissionMapper.insert(role.getId(),pid);
            }
        }
    }

    @Override
    public Role queryRoleAndPermissionsById(Integer id) throws Exception {
        return roleMapper.queryRoleAndPermissionsById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Role role, Integer[] permissionIds) throws Exception {
        //修改角色信息
        this.update(role);

        //修改权限中间表
        //删除这个角色所有的权限
        rolePermissionMapper.deleteByRoleid(role.getId());

        //重新添加权限
        if(permissionIds!=null && permissionIds.length > 0) {
            for (Integer pid : permissionIds) {
                rolePermissionMapper.insert(role.getId(), pid);
            }
        }
    }

}
